package com.gxa.order.common;


import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class UploadController {



    public Object upload(MultipartFile file){


        Map<String,Object> map = new HashMap<>();
        map.put("status",200);
        List<Map<String,Object>> result = new ArrayList<>();
        map = singleFileUpload(file);
        map.put("data",result);
        return map;
    }

    //获取配置路径

    private String uploadFilePath;

    private Map<String, Object> singleFileUpload(MultipartFile files) {
        uploadFilePath=System.getProperty("user.dir")+"/upload";

        Map<String,Object> map = new HashMap<>();
        //防止因文件名重复导致文件丢失
        String path = new String(uploadFilePath+"_"+UUID.randomUUID().toString().replace("-","").toLowerCase());
        //文件路径
        File dest =new File(path+File.separator+ files.getOriginalFilename());
        if(!dest.getParentFile().exists()){
            //避免文件创建失败,如果文件夹不存在，则创建
            dest.getParentFile().mkdirs();
        }
        try {
            files.transferTo(dest);
            map.put("url",dest);
            map.put("fileName",files.getOriginalFilename());
            map.put("success",1);
            map.put("result","文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            map.put("success",2);
            map.put("result","文件上传失败");
        }
        return map;
        //返回文件名乱码问题
        //HttpHeaders headers = new HttpHeaders();
        //MediaType mediaType = new MediaType("text","html", Charset.forName("utf-8"));
        //headers.setContentType(mediaType);
        //return new ResponseEntity<String>(js,headers, HttpStatus.OK);
    } }
